package com.wqc.count;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 限流 -- 计数法（信号量）
 */
public class CountRateLimiter {

    // Semaphore
    private static Semaphore semphore = new Semaphore(5);

    public static void exec() {
        if(semphore.getQueueLength()>10){
            System.out.println("当前等待排队的任务数大于10，请稍候再试...");
        }
        try {
            System.out.println("业务处理前");
            semphore.acquire();
            // 处理核心逻辑
            TimeUnit.SECONDS.sleep(5);
            System.out.println("业务处理完成: " + System.currentTimeMillis() / 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semphore.release();
        }
    }
}
